#!/usr/bin/env node
const bcrypt = require('bcrypt');
const { UserModel } = require('../src/models');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

function initials(text) {
  const t = String(text || '').trim();
  if (!t) return '?';
  const parts = t.split(/\s+|_|-/).filter(Boolean);
  if (parts.length >= 2) return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
  return t.slice(0, 2).toUpperCase();
}

function pickBg(text) {
  const h = crypto.createHash('sha256').update(text).digest();
  const hue = Math.floor(h[0] / 255 * 360);
  const sat = 70; // 70%
  const light = 55; // 55%
  return `hsl(${hue}, ${sat}%, ${light}%)`;
}

function buildSvg(text, size = 128) {
  const init = initials(text);
  const bg = pickBg(text);
  const radius = Math.floor(size / 2);
  const fontSize = Math.floor(size * 0.5);
  return `<?xml version="1.0" encoding="UTF-8"?>\n` +
    `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">\n` +
    `  <circle cx="${radius}" cy="${radius}" r="${radius}" fill="${bg}"/>\n` +
    `  <text x="50%" y="50%" fill="#fff" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial" font-size="${fontSize}" font-weight="700" text-anchor="middle" dominant-baseline="central">${init}</text>\n` +
    `</svg>\n`;
}

async function main() {
  const [username, password] = process.argv.slice(2);

  if (!username || !password) {
    console.error('用法: node scripts/addUser.js <username> <password>');
    process.exit(1);
  }

  try {
    // 如果已存在则提示并退出
    const existed = await UserModel.getUserByUsername(username);
    if (existed) {
      console.error(`用户名已存在: ${username}`);
      process.exit(2);
    }

    const hash = await bcrypt.hash(password, 10);

    // 生成头像到 uploads 并得到 URL
    const uploadsDir = path.join(__dirname, '..', 'uploads');
    if (!fs.existsSync(uploadsDir)) fs.mkdirSync(uploadsDir, { recursive: true });
    const fname = `avatar-${Date.now()}-${crypto.randomInt(0, 1e9)}.svg`;
    const fpath = path.join(uploadsDir, fname);
    fs.writeFileSync(fpath, buildSvg(username, 128), 'utf8');
    const avatarUrl = `/uploads/${fname}`;

    // 默认值：nickname=用户名，type=2(普通用户)，organization_id=1
    const id = await UserModel.createUser({
      username,
      password: hash,
      nickname: username,
      avatar: avatarUrl,
      type: 2,
      organization_id: 1
    });

    console.log(JSON.stringify({
      message: '用户创建成功',
      id,
      username,
      avatar: avatarUrl
    }, null, 2));
    process.exit(0);
  } catch (err) {
    console.error('创建失败:', err.message || err);
    process.exit(1);
  }
}

console.log('aa')

main();